package prj.carmap.mobile.activity;

import java.util.Vector;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import prj.carmap.mobile.CarmapApplication;
import prj.carmap.mobile.R;
import prj.carmap.mobile.model.UserInfo;
import prj.carmap.mobile.process.AutoServiceProcess;
import prj.carmap.mobile.process.BMapGeneralListener;
import prj.carmap.mobile.process.LiveServiceProcess;
import prj.carmap.mobile.process.MyLocationProcess;
import prj.carmap.mobile.process.SellerTypeProcess;
import prj.carmap.mobile.util.AccessLogUtil;
import prj.carmap.mobile.view.ScaleView;
import prj.carmap.mobile.view.ZoomControlView;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Window;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MKMapStatus;
import com.baidu.mapapi.map.MKMapStatusChangeListener;
import com.baidu.mapapi.map.MKMapViewListener;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.PopupClickListener;
import com.baidu.mapapi.map.PopupOverlay;
import com.baidu.mapapi.map.MyLocationOverlay.LocationMode;
import com.baidu.mapapi.utils.DistanceUtil;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.miaowang.salad.activity.MineInfoActivity;
import com.miaowang.salad.activity.SaladMainActivity;

/**
 * 主界面
 * 
 */
public class MainActivity extends SherlockActivity {
	private Toast mToast;
	final static String TAG = "MainActivity";

	/** 地图主控件 */
	private MapView mMapView = null;

	/** 用MapController完成地图控制 */
	private MapController mMapController = null;

	private ScaleView mScaleView;
	private ZoomControlView mZoomControlView;

	// /** MKMapViewListener 用于处理地图事件回调 */
	// MKMapViewListener mMapListener = null;

	/** 当前地图缩放比例 */
	private float currentZoom = 16;

	/** 百度地图管理器 */
	private BMapManager bMapManager;

	/** 是否首次定位 */
	boolean isFirstLoc = true;
	private boolean isRequest = false;// 是否手动触发请求定位

	private PopupOverlay mPopupOverlay = null;// 弹出泡泡图层，浏览节点时使用
	private View viewCache;
	private BDLocation location;

	/** 定位相关 */
	LocationClient mLocClient;
	private LocationData mLocData;

	// 定位图层
	private LocationOverlay myLocationOverlay = null;

	/**  */
	MyLocationProcess process = new MyLocationProcess(this);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
		super.onCreate(savedInstanceState);

		CarmapApplication.currentPage = "";
		CarmapApplication.addActivity(this);

		/**
		 * 使用地图sdk前需先初始化BMapManager. BMapManager是全局的，可为多个MapView共用，它需要地图模块创建前创建，
		 * 并在地图地图模块销毁后销毁，只要还有地图模块在使用，BMapManager就不应该销毁
		 */
		if (bMapManager == null) {
			bMapManager = new BMapManager(getApplicationContext());
			// 如果BMapManager没有初始化则初始化BMapManager
			bMapManager.init(CarmapApplication.strKey, new BMapGeneralListener(
					CarmapApplication.getInstance()));
		}

		setContentView(R.layout.activity_main);

		initActionBar();

		// 隐藏ActionBar
		getSupportActionBar().setDisplayShowCustomEnabled(false);
		getSupportActionBar().setDisplayShowHomeEnabled(false);
		getSupportActionBar().setDisplayShowTitleEnabled(false);
		getSupportActionBar().setBackgroundDrawable(null);

		// 得到地图View
		mMapView = (MapView) findViewById(R.id.bmapView);
		// 获取地图控制器
		mMapController = mMapView.getController();
		// 设置地图是否响应点击事件 .
		mMapController.enableClick(true);
		// 设置地图缩放级别
		mMapController.setZoom(currentZoom);
		// 隐藏自带的地图缩放控件
		mMapView.setBuiltInZoomControls(false);

		mScaleView = (ScaleView) findViewById(R.id.scaleView);
		mScaleView.setMapView(mMapView);
		mZoomControlView = (ZoomControlView) findViewById(R.id.ZoomControlView);
		mZoomControlView.setMapView(mMapView);

		viewCache = LayoutInflater.from(this)
				.inflate(R.layout.pop_layout, null);
		mPopupOverlay = new PopupOverlay(mMapView, new PopupClickListener() {

			@Override
			public void onClickedPopup(int arg0) {
				mPopupOverlay.hidePop();
			}
		});

		// 点击按钮手动请求定位
		((Button) findViewById(R.id.request))
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						requestLocation();
					}
				});

		// 由于MapView在setContentView()中初始化，所以它需要在BMapManager初始化之后

		process.setContext(this);
		process.setMapView(mMapView);

		// 得到广告View，广告显示在地图下方
		GridView gridView = (GridView) this.findViewById(R.id.advert_pic);
		process.setGridView(gridView);

		// 设定点击广告时的监听
		gridView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {
				JSONObject json = (JSONObject) ((GridView) parent).getAdapter()
						.getItem(position);
				try {
					String link = json.getString("advertLink");
					if (link != null && !"".equals(link)) {
						if (link.startsWith("http") || link.startsWith("https")) {
						} else {
							link = "http://" + link;
						}
						Uri uri = Uri.parse(link);
						Intent intent = new Intent(Intent.ACTION_VIEW, uri);
						startActivity(intent);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		});
		process.getAllMapData();
		// 地图显示事件监听器。 该接口监听地图显示事件，用户需要实现该接口以处理相应事件。
		mMapView.regMapViewListener(bMapManager, new MKMapViewListener() {

			@Override
			public void onMapMoveFinish() {
				refreshScaleAndZoomControl();
			}

			@Override
			public void onMapLoadFinish() {

			}

			/**
			 * 动画结束时会回调此消息.我们在此方法里面更新缩放按钮的状态
			 */
			@Override
			public void onMapAnimationFinish() {
				refreshScaleAndZoomControl();
			}

			@Override
			public void onGetCurrentMap(Bitmap arg0) {

			}

			@Override
			public void onClickMapPoi(MapPoi arg0) {

			}
		});

		refreshScaleAndZoomControl();

		// 实现对地图状态改变的处理
		MKMapStatusChangeListener listener = new MKMapStatusChangeListener() {
			GeoPoint lastGeo = new GeoPoint(0, 0);
			double distance = Double.MAX_VALUE;

			public void onMapStatusChange(MKMapStatus mapStatus) {
				float zoom = mapStatus.zoom; // 地图缩放等级
				// int overlooking = mapStatus.overlooking; // 地图俯视角度
				// int rotate = mapStatus.rotate; // 地图旋转角度
				GeoPoint nowGeo = mapStatus.targetGeo; // 中心点的地理坐标
				// Point targetScreen = mapStatus.targetScreen; // 中心点的屏幕坐标

				Log.i("sss MapStatusChange", nowGeo.getLongitudeE6() * 1e-6
						+ ", " + nowGeo.getLatitudeE6() * 1e-6);

				if (lastGeo != null) {
					distance = DistanceUtil.getDistance(nowGeo, lastGeo);
				}

				if (distance > 1000) {
					process.refreshMap(nowGeo.getLongitudeE6() * 1e-6,
							nowGeo.getLatitudeE6() * 1e-6);

					lastGeo.setLongitudeE6(nowGeo.getLongitudeE6());
					lastGeo.setLatitudeE6(nowGeo.getLatitudeE6());
				}

				if (process != null && currentZoom != zoom) {
					currentZoom = zoom;
					process.resetTextOverlay();
				}

				// TODO 根据放大级别控制是否显示商家点
			}
		};

		// 为 mapview 注册地图状态监听者。
		mMapView.regMapStatusChangeListener(listener);

		// 定位初始化
		mLocData = new LocationData();
		// 实例化定位服务，LocationClient类必须在主线程中声明
		mLocClient = new LocationClient(getApplicationContext());
		mLocClient.registerLocationListener(new MyLocationListenner());// 注册定位监听接口

		CarmapApplication.getInstance().setLocData(mLocData);

		/**
		 * 设置定位参数
		 */
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true); // 打开GPRS
		option.setAddrType("all");// 返回的定位结果包含地址信息
		option.setCoorType("bd09ll");// 返回的定位结果是百度经纬度,默认值gcj02
		option.setScanSpan(5000); // 设置发起定位请求的间隔时间为5000ms
		option.disableCache(false);// 禁止启用缓存定位
		mLocClient.setLocOption(option);
		mLocClient.start();

		// 定位图层初始化
		myLocationOverlay = new LocationOverlay(mMapView);
		// 设置定位数据
		myLocationOverlay.setData(mLocData);

		// myLocationOverlay.setMarker(getResources().getDrawable(R.drawable.location_arrows));
		// 添加定位图层
		mMapView.getOverlays().add(myLocationOverlay);
		myLocationOverlay.enableCompass();
		// myLocationOverlay.setLocationMode(LocationMode.FOLLOWING);
		// 修改定位数据后刷新图层生效
		mMapView.refresh();

		/*
		 * //版本更新检查 new UpdateVersionTask(this).checkVersion();
		 * 
		 * //分类信息加载 SellerTypeProcess typeProcess = new SellerTypeProcess();
		 * typeProcess.setContext(this); typeProcess.setFetchOnly(true);
		 * typeProcess.getSellerTypes();
		 */
	}
	

	/**
	 * 手动请求定位的方法
	 */
	public void requestLocation() {
		isRequest = true;

		if (mLocClient != null && mLocClient.isStarted()) {
			showToast("正在定位......");
			mLocClient.requestLocation();
		} else {
			Log.d("LocSDK3", "locClient is null or not started");
		}
	}

	/**
	 * 显示Toast消息
	 * 
	 * @param msg
	 */
	private void showToast(String msg) {
		if (mToast == null) {
			mToast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
		} else {
			mToast.setText(msg);
			mToast.setDuration(Toast.LENGTH_SHORT);
		}
		mToast.show();
	}

	private void initActionBar() {
		Log.d(TAG, "initActionBar");
        //汽车服务
		View view = (View) this.findViewById(R.id.menu_item_home);
		view.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				AutoServiceProcess process = new AutoServiceProcess();
				process.setContext(MainActivity.this);
				process.getSellerTypes();
			}

		});
        // 生活服务
		view = (View) this.findViewById(R.id.menu_item_type);
		view.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				LiveServiceProcess process = new LiveServiceProcess();
				process.setContext(MainActivity.this);
				process.getSellerTypes();
			}

		});

		view = (View) this.findViewById(R.id.menu_item_mine);
		view.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
//				UserInfo userInfo = CarmapApplication.getInstance().userInfo;
//				if (userInfo == null) {
//					MainActivity.this.startActivity(new Intent(
//							MainActivity.this, LoginActivity.class));
//				} else {
//					MainActivity.this.startActivity(new Intent(
//							MainActivity.this, ProfileActivity.class));
//				}
				MainActivity.this.startActivity(new Intent(
						MainActivity.this, MineInfoActivity.class));
			}

		});
		
		View saladView = (View) this.findViewById(R.id.menu_item_salad);
		saladView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this, SaladMainActivity.class);
//				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				MainActivity.this.startActivity(intent);
			}
			
		});

		// view = (View) this.findViewById(R.id.menu_item_more);
		// view.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// MainActivity.this.startActivity(new Intent(MainActivity.this,
		// MoreActivity.class));
		// }
		//
		// });

		// view = (View) this.findViewById(R.id.menu_item_search);
		// view.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// CarmapApplication.popView = new DialogView(MainActivity.this);
		// CarmapApplication.popView.show();
		// MainActivity.this.startActivity(new Intent(MainActivity.this,
		// SellerSearchActivity.class));
		// }
		//
		// });
	}

	/**
	 * 修改位置图标
	 * 
	 * @param marker
	 */
	public void modifyLocationOverlayIcon(Drawable marker) {
		// 当传入marker为null时，使用默认图标绘制
		myLocationOverlay.setMarker(marker);
		// 修改图层，需要刷新MapView生效
		mMapView.refresh();
	}

	@Override
	protected void onPause() {
		/**
		 * MapView的生命周期与Activity同步，当activity挂起时需调用MapView.onPause()
		 */
		mMapView.onPause();
		super.onPause();
	}

	private void refreshScaleAndZoomControl() {
		// 更新缩放按钮的状态
		Log.i("sss", "level" + mMapView.getZoomLevel());
		mZoomControlView.refreshZoomButtonStatus(Math.round(mMapView
				.getZoomLevel()));
		mScaleView.refreshScaleView(Math.round(mMapView.getZoomLevel()));
	}

	@Override
	protected void onResume() {
		/**
		 * MapView的生命周期与Activity同步，当activity恢复时需调用MapView.onResume()
		 */
		mMapView.onResume();
		super.onResume();
		CarmapApplication.currentPage = "";
	}

	@Override
	protected void onDestroy() {
		/**
		 * MapView的生命周期与Activity同步，当activity销毁时需调用MapView.destroy()
		 */
		// 退出时销毁定位
		if (mLocClient != null)
			mLocClient.stop();
		mMapView.destroy();
		super.onDestroy();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mMapView.onSaveInstanceState(outState);

	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		mMapView.onRestoreInstanceState(savedInstanceState);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			dialog();
			return true;
		}
		return true;
	}

	// private void showPopupOverlay(BDLocation location){
	// TextView popText =
	// ((TextView)viewCache.findViewById(R.id.location_tips));
	// popText.setText("[我的位置]\n" + location.getAddrStr());
	// mPopupOverlay.showPopup(getBitmapFromView(popText),
	// new GeoPoint((int)(location.getLatitude()*1e6),
	// (int)(location.getLongitude()*1e6)),
	// 10);
	// }

	/**
	 * 
	 * @param view
	 * @return
	 */
	public static Bitmap getBitmapFromView(View view) {
		view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
				MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
		view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
		view.buildDrawingCache();
		Bitmap bitmap = view.getDrawingCache();
		return bitmap;
	}

	protected void dialog() {
		AlertDialog.Builder builder = new Builder(this);
		builder.setMessage("确定要退出吗?");
		builder.setTitle("提示");
		builder.setPositiveButton("确认",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						Vector<Activity> ac = CarmapApplication.activities;
						for (Activity a : ac) {
							a.finish();
						}
						android.os.Process.killProcess(android.os.Process
								.myPid());
						// 发送退出log给服务器
						StringEntity log = AccessLogUtil
								.createAccessLogTypeParam(3);
						if (log != null)
							new AsyncHttpClient().post(MainActivity.this,
									CarmapApplication.SERVER_URL
											+ "/rest/accesslog", log,
									"application/json",
									new AsyncHttpResponseHandler());
					}
				});
		builder.setNegativeButton("取消",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		builder.create().show();
	}

	//
	private class LocationOverlay extends MyLocationOverlay {

		public LocationOverlay(MapView arg0) {
			super(arg0);
		}

		@Override
		protected boolean dispatchTap() {
			// showPopupOverlay(location);
			return super.dispatchTap();
		}

		@Override
		public void setMarker(Drawable arg0) {
			super.setMarker(arg0);
		}

	}

	/**
	 * 定位SDK监听函数
	 */
	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null)
				return;

			MainActivity.this.location = location;

			/*
			 * LocationData locData =
			 * CarmapApplication.getInstance().getLocData(); double distance =
			 * DistanceUtil.getDistance( new GeoPoint((int) (locData.latitude *
			 * 1e6), (int) (locData.longitude * 1e6)), new GeoPoint((int)
			 * (location.getLatitude() * 1e6), (int) (location.getLongitude() *
			 * 1e6)) ); if (distance < 10) { return; }
			 */

			Log.i("sss BDLocationListener", location.getLongitude() + ", "
					+ location.getLatitude());

			mLocData.latitude = location.getLatitude();
			mLocData.longitude = location.getLongitude();
			// mLocData.latitude = 30.67;
			// mLocData.longitude = 104.06;
			// 如果不显示定位精度圈，将accuracy赋值为0即可
			mLocData.accuracy = location.getRadius();
			// 此处可以设置 locData的方向信息, 如果定位 SDK 未返回方向信息，用户可以自己实现罗盘功能添加方向信息。
			mLocData.direction = location.getDerect();
			// 更新定位数据
			myLocationOverlay.setData(mLocData);
			// 更新图层数据执行刷新后生效
			mMapView.refresh();
			// 是手动触发请求或首次定位时，移动到定位点
			if (isFirstLoc || isRequest) {
				// 移动地图到定位点
				Log.d("LocationOverlay", "receive location, animate to it");
				mMapController.animateTo(new GeoPoint((int) (location
						.getLatitude() * 1e6),
						(int) (location.getLongitude() * 1e6)));
				// (int) (30.67 * 1e6),
				// (int) (104.06 * 1e6)));
				// showPopupOverlay(location);
				myLocationOverlay.setLocationMode(LocationMode.NORMAL);
				isRequest = false;
			}
			// 首次定位完成
			isFirstLoc = false;
			// process.refreshMap(location.getLongitude(),
			// location.getLatitude());
		}

		public void onReceivePoi(BDLocation poiLocation) {
			if (poiLocation == null) {
				return;
			}
		}
	}

}
